package com.fay.basic.base.copy.reflection;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/5/13 17:13
 * @Version 1.0
 */
public class ConstructorReflectForNewInstance {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 获取User类型
        Class<User> userClass = User.class;
        // 获取默认构造器  NoSuchMethodException
        Constructor<User> constructor = userClass.getConstructor();
        // 获取带int参数的构造器
        Constructor<User> intConstructor = userClass.getConstructor(int.class);
        // 获取带int 和 String类型的构造器
        Constructor<User> twoArgsConstructor = userClass.getConstructor(int.class, String.class);

        // 使用反射，获取新的User对象  InvocationTargetException 调用激活方法无效  InstantiationException  IllegalAccessException 不能调入的方法
        User user = constructor.newInstance();
        User user1 = intConstructor.newInstance(1);
        User user2 = twoArgsConstructor.newInstance(2, "fay");

        System.out.println(user);
        System.out.println(user1);
        System.out.println(user2);
    }
}

@AllArgsConstructor
@NoArgsConstructor
@Data
class User {
    private int id;
    private String name;

    public User(int id) {
        this.id = id;
    }
}
